package com.itheima.admin.controller;

import com.itheima.admin.service.CategoryService;
import com.itheima.xo.common.Result;
import com.itheima.xo.pojo.Category;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


/**
 * @author :WuJunJie
 * packageName :com.itheima.admin.controller
 * fileName :CategoryController
 * creationTime :2022-10-28 18:28
 */
@RestController
@RequestMapping("category")
@Slf4j
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @PostMapping("add")
    public Result add(@RequestBody Category category) {
        if (!nameLength(category.getCategoryName())) {
            log.info("分类名“{}”的长度大于20，无法创建", category.getCategoryName());
            return Result.error();
        }
        if (category.getCategoryName()==null||category.getCategoryName().trim().length()==0){
            log.info("分类名不能为空");
            return Result.error();
        }
        Boolean add = categoryService.add(category);
        if (add) {
            return Result.success(null);
        }
            return Result.error();


    }

    @DeleteMapping("delete/{id}")
    public Result delete(@PathVariable String id) {
        log.info("delet:::{}",id);
        Boolean delete = categoryService.delete(id);
        if (delete) {
            return Result.success(null);
        }

        return Result.error();

    }

    @PutMapping("update")
    public Result update(@RequestBody Category category) {
        if (!nameLength(category.getCategoryName())){
            log.info("分类名“{}”的长度大于20，无法更改", category.getCategoryName());
            return Result.error();
        }
        Boolean update = categoryService.update(category);
        if (update) {
            return Result.success(null);
        }

        return Result.error();

    }

    @GetMapping("findAll")
    public Result findAll() {
        return Result.success(categoryService.findAll());
    }

    @GetMapping("findById/{id}")
    public Result findById(@PathVariable String id) {
        return Result.success(categoryService.findById(id));
    }

    private Boolean nameLength(String name) {
        if (name == null) {
            return true;
        }
        return name.length() <= 20;
    }

}
